<template>
  <div class="user-management">
    <el-card class="management-card">
      <template #header>
        <div class="card-header">
          <span>用户管理 (优化版)</span>
          <el-button type="primary" @click="showCreateDialog">
            <el-icon><Plus /></el-icon>
            添加用户
          </el-button>
        </div>
      </template>

      <!-- 使用通用数据表格组件 -->
      <DataTable
        :data="tableData.data.value"
        :columns="columns"
        :loading="tableData.loading.value"
        :pagination="tableData.pagination"
        @search="tableData.actions.search"
        @refresh="tableData.actions.refresh"
        @selection-change="handleSelectionChange"
        @page-change="tableData.actions.changePage"
        @page-size-change="tableData.actions.changePageSize"
        @batch-delete="handleBatchDelete"
      >
        <!-- 状态列插槽 -->
        <template #status="{ row }">
          <el-tag :type="row.is_active ? 'success' : 'danger'">
            {{ row.is_active ? '激活' : '禁用' }}
          </el-tag>
        </template>

        <!-- 角色列插槽 -->
        <template #roles="{ row }">
          <el-tag
            v-for="role in row.roles"
            :key="role.id"
            size="small"
            class="role-tag"
          >
            {{ role.name }}
          </el-tag>
        </template>

        <!-- 操作列插槽 -->
        <template #actions="{ row }">
          <el-button
            type="primary"
            size="small"
            @click="showEditDialog(row)"
          >
            编辑
          </el-button>
          <el-button
            type="warning"
            size="small"
            @click="toggleUserStatus(row)"
          >
            {{ row.is_active ? '禁用' : '启用' }}
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="deleteUser(row.id)"
          >
            删除
          </el-button>
        </template>
      </DataTable>
    </el-card>

    <!-- 使用通用表单对话框组件 -->
    <FormDialog
      v-model="dialogVisible"
      :form-data="formData.formData"
      :rules="formRules"
      :loading="formData.loading.value"
      :is-edit="formData.isEdit.value"
      @submit="handleSubmit"
      @cancel="handleCancel"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="formData.formData.username"
          placeholder="请输入用户名"
          :disabled="formData.isEdit.value"
        />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input
          v-model="formData.formData.email"
          placeholder="请输入邮箱"
          type="email"
        />
      </el-form-item>

      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="formData.formData.phone"
          placeholder="请输入手机号"
        />
      </el-form-item>

      <el-form-item label="角色" prop="role_ids">
        <el-select
          v-model="formData.formData.role_ids"
          multiple
          placeholder="请选择角色"
        >
          <el-option
            v-for="role in roles"
            :key="role.id"
            :label="role.name"
            :value="role.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item v-if="!formData.isEdit.value" label="密码" prop="password">
        <el-input
          v-model="formData.formData.password"
          placeholder="请输入密码"
          type="password"
          show-password
        />
      </el-form-item>

      <el-form-item v-if="!formData.isEdit.value" label="确认密码" prop="password_confirm">
        <el-input
          v-model="formData.formData.password_confirm"
          placeholder="请确认密码"
          type="password"
          show-password
        />
      </el-form-item>
    </FormDialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import DataTable from '@/components/DataTable.vue'
import FormDialog from '@/components/FormDialog.vue'
import { useTable } from '@/composables/useTable'
import { useCrudForm } from '@/composables/useForm'
import api from '@/utils/api'
import type { TableColumn } from '@/components/DataTable.vue'

// 表格列定义
const columns: TableColumn[] = [
  { prop: 'username', label: '用户名', width: 120 },
  { prop: 'email', label: '邮箱', minWidth: 180 },
  { prop: 'phone', label: '手机号', width: 130 },
  { prop: 'roles', label: '角色', slot: 'roles', minWidth: 150 },
  { prop: 'is_active', label: '状态', slot: 'status', width: 80, align: 'center' },
  { prop: 'date_joined', label: '创建时间', width: 180, align: 'center' }
]

// 表单初始数据
const initialFormData = {
  username: '',
  email: '',
  phone: '',
  password: '',
  password_confirm: '',
  role_ids: []
}

// 表单验证规则
const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  password_confirm: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== formData.formData.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// API 函数
const fetchUsers = (params: any) => api.get('/rbac/users/', { params })
const createUser = (data: any) => api.post('/auth/register/', data)
const updateUser = (id: number, data: any) => api.put(`/rbac/users/${id}/`, data)
const deleteUserApi = (id: number) => api.delete(`/rbac/users/${id}/`)

// 使用表格Hook
const tableData = useTable(fetchUsers, deleteUserApi, {
  immediate: true,
  pageSize: 10
})

// 使用表单Hook
const formData = useCrudForm(initialFormData, {
  createFn: createUser,
  updateFn: updateUser,
  onSuccess: () => {
    dialogVisible.value = false
    tableData.actions.refresh()
  }
})

// 响应式数据
const dialogVisible = ref(false)
const roles = ref([])

// 获取角色列表
const fetchRoles = async () => {
  try {
    const response = await api.get('/rbac/roles/')
    if (response.data.success) {
      roles.value = response.data.data.results || response.data.data
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
  }
}

// 事件处理
const showCreateDialog = () => {
  formData.setCreateMode()
  dialogVisible.value = true
}

const showEditDialog = (user: any) => {
  formData.setEditMode(user.id, {
    username: user.username,
    email: user.email,
    phone: user.phone,
    role_ids: user.roles.map((role: any) => role.id)
  })
  dialogVisible.value = true
}

const handleSubmit = () => {
  formData.submitForm()
}

const handleCancel = () => {
  dialogVisible.value = false
}

const handleSelectionChange = (selection: any[]) => {
  // 处理选择变化
}

const handleBatchDelete = (selection: any[]) => {
  const ids = selection.map(item => item.id)
  // 实现批量删除逻辑
  ElMessage.info('批量删除功能开发中...')
}

const deleteUser = (id: number) => {
  tableData.actions.deleteItem(id)
}

const toggleUserStatus = async (user: any) => {
  try {
    const response = await api.patch(`/rbac/users/${user.id}/`, {
      is_active: !user.is_active
    })
    
    if (response.data.success) {
      ElMessage.success(`用户已${user.is_active ? '禁用' : '启用'}`)
      tableData.actions.refresh()
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 初始化
onMounted(() => {
  fetchRoles()
})
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.management-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.role-tag {
  margin-right: 4px;
  margin-bottom: 4px;
}
</style>
